package com.example.spring_blog.common.advice;

import com.example.spring_blog.common.exception.BlogException;
import com.example.spring_blog.pojo.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

import java.util.List;

@Slf4j
@ResponseBody
@ControllerAdvice
public class ExceptionAdvice {
    @ExceptionHandler
    public Result exceptionHandler(Exception exception) {
        log.error("发生异常, e:", exception);
        return Result.fail(exception.getMessage());
    }

    @ExceptionHandler
    public Result exceptionHandler(BlogException exception) {
        log.error("发生异常, e: {}", exception.getErrMsg());
        return Result.fail(exception.getErrMsg());
    }

    // 在方法的参数中的validation注解比如@NotNull，如果不满足则报错HandlerMethodValidationException
    @ExceptionHandler
    public Result exceptionHandler(HandlerMethodValidationException exception) {
        log.error("发生异常, e:{}", exception.getMessage());
        return Result.fail("参数校验失败");
    }

    // 在类中给属性绑定validation注解比如@NotNull，此时如果不满足则报错MethodArgumentNotValidException
    @ExceptionHandler
    public Result exceptionHandler(MethodArgumentNotValidException exception) {
        // 拿到MethodArgumentNotValidException中的默认的失败信息
        String msg = exception.getBindingResult().getFieldError().getDefaultMessage();
        log.error("发生异常, e:{}", exception.getMessage());
        return Result.fail(msg);
    }
}
